package win.larryzeal.jms.queue.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;
import win.larryzeal.jms.common.Common;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * Created by 张少昆 on 2017/8/4 0004.
 */
public class MyJmsQueueConsumer {
	public static void main(String[] args){
		//1, connectionFactory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Common.url);
		//2, create connection
		Connection connection = null;
		Session session = null;
		try{
			connection = connectionFactory.createConnection();
			//3, start the connection
			connection.start();

			boolean transactioned = false;
			//4, start a session
			session = connection.createSession(transactioned, Session.AUTO_ACKNOWLEDGE);//不开启事务；自动应答机制

			//5, set the destination
			Queue queue = session.createQueue(Common.queueName);//NOTE Queue extends Destination

			//6, create consumer
			MessageConsumer consumer = session.createConsumer(queue);

			//7, register listener
			consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message){
					TextMessage msg = (TextMessage) message;
					try{
						System.out.println("收到消息：" + msg.getText());
					} catch(JMSException e){
						e.printStackTrace();
					}
				}
			});
		} catch(JMSException e){
			e.printStackTrace();
		} /*finally{
			try{
				if(session != null)
					session.close();
//				if(connection != null)
				connection.close();
			} catch(JMSException e){
				e.printStackTrace();
			}
		}*/
	}
}
